package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;


    /**
     * 处理添加套餐的请求
     * @param setmealDto
     * @param session
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto, HttpSession session){
        //1.获取登录人
        Long id = (Long) session.getAttribute("employee");

        //2.完善套餐数据(更新人,创建人)
        setmealDto.setUpdateUser(id);
        setmealDto.setCreateUser(id);

        //3.调用业务实现添加套餐
        setmealService.save(setmealDto);

        //4.返回数据
        return R.success("添加套餐成功");
    }


    /**
     * 处理套餐页面请求
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
   public R<Page<SetmealDto>> findByPage(Integer page,Integer pageSize, String name){

        //调用业务查询套餐分页数据方法
        Page<SetmealDto> byPage = setmealService.findByPage(page, pageSize, name);

        //返回数据
        return R.success(byPage);

    }

    /**
     * 批量删除套餐
     * @param ids
     * @param session
     * @return
     */
    @DeleteMapping
    //@RequestParam加上这个注解springmvc就将前端传递过来的数据封装成一个list集合,如果不加默认封装成数组
    public R<String> deleteByIds(@RequestParam List<Long> ids,HttpSession session){
        //获取操作人
        Long  id = (Long) session.getAttribute("employee");

        //调用业务方法删除
        setmealService.deleteByIds(ids,id);

        //返回数据
        return R.success("删除套餐成功");
    }


    /**
     * 修改套餐回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Setmeal> findById(@PathVariable Long id){
        SetmealDto byId = setmealService.findById(id);
        return R.success(byId);
    }


    /**
     * 修改套餐
     * @param setmealDto
     * @param session
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto,HttpSession session){
        Long id = (Long) session.getAttribute("employee");

        setmealDto.setUpdateUser(id);

        setmealService.updates(setmealDto);

        return R.success("修改套餐成功");
    }

}
